<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC 麦克风监听与录音上传</title>
</head>
<body>
    <h1>麦克风声音监听与录音上传</h1>
    <p id="status">状态: 未开始</p>

    <!-- 按钮 -->
    <button id="startBtn">开始监听</button>
    <button id="stopBtn" disabled>停止监听</button>
    <button id="playBtn" disabled>播放音频</button> <!-- 播放音频按钮 -->

    <!-- 播放返回的音频 -->
    <audio id="audioPlayer" controls style="display:none;"></audio>

    <script>
        let audioContext, analyser, microphone;
        let mediaRecorder;
        let audioChunks = [];
        let listening = false; // 标记监听状态
        let silenceTimer;
        let audioPath = ""; // 用于保存音频路径
        const threshold = 200; // 声音阈值
        const silenceTimeout = 400; // 静音延迟时间 (ms)

        const statusElement = document.getElementById("status");
        const audioPlayer = document.getElementById("audioPlayer");

        // 开始监听麦克风
        async function startListening() {
            if (listening) return;
            listening = true;
            statusElement.textContent = "状态: 正在监听麦克风...";

            // 检查是否支持 getUserMedia
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });

                    // 初始化 AudioContext 和分析器
                    audioContext = new (window.AudioContext || window.webkitAudioContext)();
                    analyser = audioContext.createAnalyser();

                    microphone = audioContext.createMediaStreamSource(stream);
                    microphone.connect(analyser);

                    analyser.fftSize = 256; // 设置 FFT 大小
                    const bufferLength = analyser.frequencyBinCount;
                    const dataArray = new Uint8Array(bufferLength);

                    checkSound(dataArray); // 开始检测声音

                    // 初始化录音器
                    mediaRecorder = new MediaRecorder(stream);
                    mediaRecorder.ondataavailable = (event) => {
                        audioChunks.push(event.data);
                    };
                    mediaRecorder.onstop = () => {
                        const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                        uploadAudio(audioBlob);
                        audioChunks = []; // 清空缓存
                    };
                } catch (err) {
                    console.error("获取麦克风失败", err);
                    statusElement.textContent = "状态: 获取麦克风失败";
                    listening = false;
                }
            } else {
                alert("您的浏览器不支持麦克风访问");
            }
        }

        // 停止监听麦克风
        function stopListening() {
            if (!listening) return;
            listening = false;

            if (microphone) {
                microphone.disconnect();
                audioContext.close();
            }

            if (mediaRecorder && mediaRecorder.state !== "inactive") {
                mediaRecorder.stop();
            }

            statusElement.textContent = "状态: 监听已停止";
        }

        // 检测声音并启动录音
        function checkSound(dataArray) {
            if (!listening) return;

            requestAnimationFrame(() => checkSound(dataArray));
            analyser.getByteFrequencyData(dataArray);
            const maxAmplitude = Math.max(...dataArray);

            // 检测是否正在播放音频
            if (maxAmplitude > threshold && audioPlayer && !audioPlayer.paused) {
                // 如果正在播放音频，暂停
                audioPlayer.pause();
                statusElement.textContent = "状态: 检测到声音，停止音频播放...";
            }

            if (maxAmplitude > threshold && mediaRecorder && mediaRecorder.state === "inactive") {
                statusElement.textContent = "状态: 检测到声音，开始录音...";
                mediaRecorder.start();
            } else if (maxAmplitude <= threshold && mediaRecorder && mediaRecorder.state === "recording") {
                if (!silenceTimer) {
                    silenceTimer = setTimeout(() => {
                        mediaRecorder.stop();
                        silenceTimer = null;
                        statusElement.textContent = "状态: 检测到静音，停止录音...";
                    }, silenceTimeout);
                }
            } else if (maxAmplitude > threshold) {
                clearTimeout(silenceTimer);
                silenceTimer = null;
            }
        }

        // 上传音频
        async function uploadAudio(audioBlob) {
            const formData = new FormData();
            formData.append('audio', audioBlob, 'audio.wav');

            try {
                const response = await fetch('https://eeed-14-153-93-146.ngrok-free.app/api/audio_api/upload', {
                // const response = await fetch('http://127.0.0.1:7007/api/audio_api/upload', {
                    method: 'POST',
                    body: formData,
                });

                const data = await response.json();
                console.log("音频上传成功", data);

                // 检查接口返回状态码
                if (response.status === 200 && data && data.result) {
                    audioPath = data.result;  // 保存返回的音频路径
                    statusElement.textContent = "状态: 上传成功";

                    // 启用播放按钮并自动播放音频
                    document.getElementById("playBtn").disabled = false;
                    playAudio(); // 自动播放音频
                } else {
                    console.error("上传失败", data);
                    statusElement.textContent = "状态: 上传失败";
                }
            } catch (err) {
                console.error("上传失败", err);
                statusElement.textContent = "状态: 上传失败";
            }
        }

        // 播放音频
        function playAudio() {
            if (audioPath) {
                // 直接使用返回的音频 URL 来播放
                audioPlayer.src = audioPath;
                audioPlayer.style.display = 'block'; // 显示音频播放器
                audioPlayer.play(); // 播放音频
            } else {
                alert("没有有效的音频文件可播放！");
            }
        }

        // 按钮事件绑定
        document.getElementById('startBtn').addEventListener('click', () => {
            startListening();
            document.getElementById('startBtn').disabled = true;
            document.getElementById('stopBtn').disabled = false;
        });

        document.getElementById('stopBtn').addEventListener('click', () => {
            stopListening();
            document.getElementById('startBtn').disabled = false;
            document.getElementById('stopBtn').disabled = true;
        });

        document.getElementById('playBtn').addEventListener('click', playAudio); // 播放按钮点击事件
    </script>
</body>
</html>
